%% Hjelpefunksjoner

declare fun {MultiplyWithFive N} N * 5 end
declare fun lazy {MakeNaturals N} N|{MakeNaturals N + 1} end
declare fun lazy {MakeFloats N} N|{MakeFloats N + 1.0} end
declare fun {Multiply X Y} X*Y end
declare L = {MakeNaturals 1}
declare M = {MakeNaturals 4}
declare LF = {MakeFloats 5.0}

%% Task 2 Avbildning av strømmer

declare
fun lazy {StreamMap S F}
   case S of H|T then
      {F H}|{StreamMap T F}
   else
      nil
   end
end

%%  Testing
declare
Lmodified = {StreamMap L MultiplyWithFive}
%{Browse Lmodified.2.2.2.2.2.1}  %% 6. element * 5 => 30

%% Task 3 Slå sammen strømmer

declare
fun lazy {StreamZip S1 S2 F}
   case S1#S2 of (S1h|S1t)#(S2h|S2t) then   %% Se Ø5.pdf
      {F S1h S2h}|{StreamZip S1t S2t F}
   else
      nil
   end
end

%% Testing
declare Lzipped = {StreamZip L M Multiply}
% {Browse Lzipped.2.2.2.1} %% 1,2,3,4 * 4,5,6,7 = 4*7 => 28


%% Task 4 Skalere strømmer

declare
fun lazy {StreamScale SF Factor}
   case SF of H|T then
      (H*Factor)|{StreamScale T Factor}
   else
      nil
   end
end

%% Testing
declare Lscaled = {StreamScale LF 2.0}
%{Browse Lscaled.2.2.1} % 1,2,3 * 2 => 6.0

%% Task 5 Addere strømmer

declare
fun lazy {StreamAdd SF1 SF2}
   case SF1#SF2 of (SF1h|SF1t)#(SF2h|SF2t) then
      (SF1h + SF2h)|{StreamAdd SF1t SF2t}
   else
      nil
   end
end

%% Testing
declare Lsum = {StreamAdd LF LF}
%{Browse Lsum.2.2.2.1} % 4.0 + 4.0 => 8.0


%% Task 6 Integrere strømmer

declare
fun lazy {StreamInt SF Init Dt}
   case SF of H|T then
      Y in
      Y=(H*Dt)+Init
      Y|{StreamInt T Y Dt}
   else
      nil
   end
end

declare
fun lazy {StreamIntegrate SF InitValue Dt}
   InitValue|{StreamInt SF InitValue Dt}  
end

 

%% Testing
declare Linteg = {StreamIntegrate LF 2.0 3.0}
%{Browse [Linteg.1 Linteg.2.1 Linteg.2.2.1]}

%% Task 7 Simulere RC-kretser

declare
fun lazy {MakeRC R C Dt}
   RC in
   RC = fun lazy {$ SF V0}
	   {StreamAdd {StreamIntegrate {StreamScale SF 1.0/C} V0 Dt} {StreamScale SF R}}
	end
   RC
end

%%Testing
%declare
%fun lazy {MakeOnes} 1.0 | {MakeOnes} end
%RC = {MakeRC 5.0 1.0 0.2}
%Vs = {RC {MakeOnes} 2.0}
%{Nth Vs 5 _}
%{Browse Vs}

declare
Streams = streams(streamMap: StreamMap
		  streamZip: StreamZip
		  streamScale: StreamScale
		  streamIntegrate: StreamIntegrate
		  streamAdd: StreamAdd
		  makeRC: MakeRC)

Test={Module.link ['SimGraph.ozf']}.1.make

{Test Streams}

